package orchestration.conditions.jepImpl;

import java.util.Collection;

import orchestration.businessprocess.execution.Property;
import orchestration.conditions.IConditionEvaluator;
import orchestration.conditions.exceptions.CheckingConditionException;

import com.singularsys.jep.EvaluationException;
import com.singularsys.jep.Jep;
import com.singularsys.jep.JepException;
import com.singularsys.jep.ParseException;
/**
 * An {@link IConditionEvaluator} that uses the Java Expression Parser
 * liubrary to evaluate conditions
 * @author <a href="mailto:car.ferrarini@gmail.com">Carlo Ferrarini</a>
 *
 */
public class JepAdapter implements IConditionEvaluator{

	
	public boolean check(String condition, Collection<Property>propertiers) throws CheckingConditionException {
		Jep jep =new Jep();
		try {
			jep.parse(condition);
		} catch (ParseException e) {
			throw new CheckingConditionException("Error while parsing the expression");
		}
		for(Property pr : propertiers)
			try {
				jep.addVariable(pr.getName(), pr.getValue());
			} catch (JepException e) {
				throw new CheckingConditionException("Error while adding variables");
			}
		try {
			return ((Boolean)jep.evaluate()).booleanValue();
		} catch (EvaluationException e) {
			throw new CheckingConditionException("Error while evaluating the expression");
		}
	}

}
